<script setup lang="ts">
import { createEnvironment } from '@/api/code/environment';
import type { Environment } from '@/api/code/environment/type';
import { onMounted, onUnmounted, ref } from 'vue';

const show = defineModel("show")
const formData = ref({} as Environment);

onMounted(() => {
    if (!Array.isArray(formData.value.containerEnv)) {
        formData.value.containerEnv = [];
    }
    formData.value.containerEnv.push("");
})

const onSubmit = () => {
    createEnvironment(formData.value);
}

const addEnv = () => {
    formData.value.containerEnv.push('')
}

const reduceEnv = () => {
    if (Array.isArray(formData.value.containerEnv)) {
        if (formData.value.containerEnv.length === 1) {
            formData.value.containerEnv[0] = '';
        } else {
            formData.value.containerEnv.pop();
        }
    }
}

const cancel = () => {
    show.value = false;
}

</script>

<template>
    <div>
        <el-dialog v-model="show" title="创建环境" width="500">
            <el-form :model="formData" label-width="auto" style="max-width: 600px">
                <el-form-item label="环境名">
                    <el-input v-model="formData.name" />
                </el-form-item>
                <el-form-item label="镜像名">
                    <el-input v-model="formData.imageName" />
                </el-form-item>
                <el-form-item label="容器环境">
                    <div class="input" v-for="(item, index) in formData.containerEnv">
                        <div class="row">
                            <el-input v-model="formData.containerEnv[index]" />
                            <el-icon :size="20" class="center" @click="addEnv"><Plus /></el-icon>
                            <el-icon :size="20" class="center" @click="reduceEnv"><Minus /></el-icon>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
            <div class="row">
                <el-button @click="cancel" type="primary">取消</el-button>
                <el-button @click="onSubmit()" type="primary">提交</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.input {
    display: flex;
    flex-direction: column;
    width: 100%;
    .row {
        width: 100%;
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-bottom: 3%;
    }
}
.center {
    margin-left: 2%;
    margin-right: 2%;
}
</style>